<?php

// +---------------------------------------------------
// | Name: 星空后台 安全管理
// +----------------------------------------------------
// | Version: V5.0
// +----------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +----------------------------------------------------
// | Time: 2021-04-08 17:18
// +----------------------------------------------------
declare(strict_types=1);

namespace app\xingkong\controller\v1;

use app\common\common\BackendController;
use app\common\model\Admin as AdminModel;
use app\common\model\AdminGroup as AdminGroupModel;
use app\common\model\AdminLog as AdminLogModel;
use app\common\model\AuthRule as AuthRuleModel;
use app\common\services\AuthRuleUpdate;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;

/**
 * @xk 安全管理
 */
class Admin extends BackendController
{
    // +---------------
    // | 权限节点管理
    // +---------------

    /**
     * @xk 权限节点列表
     *
     * @method authRule
     *
     * @param AuthRuleModel $authRuleModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:27:00+080
     */
    public function authRule(AuthRuleModel $authRuleModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $list = $authRuleModel->select();
            $count = $authRuleModel->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $this->result($code, $msg, $result_code, $result_msg, $list, $count);
        }

        return View::fetch();
    }

    /**
     * @xk 权限节点更新
     *
     * @method authRuleUpdate
     *
     * @param AuthRuleUpdate $authRuleUpdate [description]
     * @param AuthRuleModel  $authRuleModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:28:48+080
     */
    public function authRuleUpdate(AuthRuleUpdate $authRuleUpdate, AuthRuleModel $authRuleModel)
    {
        $code = 200;
        $msg = '请求成功';
        try {
            // 获取系统节点
            $node_list = $authRuleUpdate->getUpNodeService();
            if (!$node_list) {
                throw new \think\Exception("权限节点不存在", 404);

            }
            clearResetDb('auth_rule'); //清空数据表 带前缀
            $controller = [];
            foreach ($node_list as $key => $value) {
                $controller['auth_name'] = $value['auth_name'];
                $controller['auth_controller'] = $value['auth_controller'];
                $controller['auth_action'] = $value['auth_action'];
                $controller['linkurl'] = $value['linkurl'];
                $controller['parent_id'] = 0;
                $controller['status'] = 1;
                $controller_res = $authRuleModel->create($controller);
                if ($value['childs']) {
                    foreach ($value['childs'] as $k => $val) {
                        $action = [];
                        $action['auth_name'] = $val['auth_name'];
                        $action['auth_controller'] = $val['auth_controller'];
                        $action['auth_action'] = $val['auth_action'];
                        $action['linkurl'] = $val['linkurl'];
                        $action['parent_id'] = $controller_res->auth_rule_id;
                        $action['status'] = 1;
                        $action_res = $authRuleModel->create($action);
                    }
                }
            }
            $result_code = 200;
            $result_msg = '权限节点更新成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 获取树形权限节点
     *
     * @method getAuthRuleTree
     *
     * @param AdminRuleModel $adminRuleModel [description]
     * @param AuthRuleModel  $authRuleModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-21T14:29:17+080
     */
    public function getAuthRuleTree(AdminGroupModel $adminGroupModel, AuthRuleModel $authRuleModel)
    {
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $admin_group_id = isset($param['admin_group_id']) ? $param['admin_group_id'] : 0;
            if ($admin_group_id > 0) {
                $nodes = $adminGroupModel->where(['admin_group_id' => $admin_group_id])->value('auth_rule_id');
                if ($nodes) {
                    $nodes_arr = explode(',', $nodes);
                } else {
                    $nodes_arr = [];
                }
            } else {
                $nodes_arr = [];
            }
            $auth_rule = $authRuleModel->getAuthRuleTree($nodes_arr);
            $result_code = 200;
            $result_msg = '请求成功';
            $resultData = $auth_rule;
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            $resultData = [];
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    // +----------------
    // | 管理组管理
    // +----------------

    /**
     * @xk 管理组列表
     *
     * @method adminGroup
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:31:48+080
     */
    public function adminGroup(AdminGroupModel $adminGroupModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $page = isset($param['page']) ? (int) $param['page'] : 1;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 30;
            $condition = [];
            if ('' != $keywords) {
                $condition[] = ['ag.group_name|ag.des', 'like', '%'.$keywords.'%'];
            }
            $list = $adminGroupModel
                  ->alias('ag')
                  ->where($condition)
                  ->field('ag.`admin_group_id`,ag.`group_name`,ag.`des`,ag.`auth_rule_name`,ag.`status`,ag.`update_time`')
                  ->withattr('des', function ($value, $data) {
                      return html_entity_decode($value);
                  })
                  ->page($page, $limit)
                  ->select();
            $count = $adminGroupModel->alias('ag')->where($condition)->count();
            $code = 200;
            $msg = '加载成功';
            $result_code = 200;
            $result_msg = '获取成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $count;
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        return View::fetch();
    }

    /**
     * @xk 管理组添加
     *
     * @method adminGroupCreate
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-21T15:09:07+080
     */
    public function adminGroupCreate()
    {
        return View::fetch();
    }

    /**
     * @xk 管理组编辑
     *
     * @method adminGroupEdit
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-21T15:08:57+080
     */
    public function adminGroupEdit(AdminGroupModel $adminGroupModel)
    {
        $param = request()->param();
        $admin_group_id = isset($param['admin_group_id']) ? $param['admin_group_id'] : 0;
        if ($admin_group_id <= 0) {
            $this->error('请选择需要操作的管理组');
            exit();
        }
        $info = $adminGroupModel->find($admin_group_id);

        return View::fetch('', ['info' => $info]);
    }

    /**
     * @xk 管理组保存
     *
     * @method adminGroupSave
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:34:34+080
     */
    public function adminGroupSave(AdminGroupModel $adminGroupModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $check_result = $adminGroupModel->validate($param, $act);
            switch ($act) {
            case 'create':
                $res = $adminGroupModel->create($param);
                break;
            case 'edit':
                $res = $adminGroupModel->find($param['admin_group_id'])->save($param);
                break;
        }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 管理组动态修改
     *
     * @method adminGroupChanageValue
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:35:11+080
     */
    public function adminGroupChanageValue(AdminGroupModel $adminGroupModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
              throw new \think\Exception("请选择需要修改的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $adminGroupModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 管理组删除
     *
     * @method adminGroupDestroy
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:35:50+080
     */
    public function adminGroupDestroy(AdminGroupModel $adminGroupModel, AdminModel $adminModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
              throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                // 开始判断是否存在管理员
                $count = 0;
                $count = $adminModel->where([['admin_group_id', '=', $value]])->count();
                if ($count > 0) {
                    ++$j;
                    continue;
                }
                $res = $adminGroupModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // +-----------------
    // | 管理员管理
    // +-----------------

    /**
     * @xk 管理员列表
     *
     * @method admin
     *
     * @param AdminModel $adminModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:36:25+080
     */
    public function admin(AdminModel $adminModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int) $param['page'] : 1;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $condition = [];
            if ('' != $keywords) {
                $condition[] = ['a.admin_name|a.admin_num|a.admin_email|a.admin_tel', 'like', '%'.$keywords.'%'];
            }
            $list = $adminModel
                ->alias('a')
                ->leftJoin('adminGroup ag', 'ag.admin_group_id=a.admin_group_id')
                ->where($condition)
                ->field('a.`admin_id`,a.`admin_name`,a.`head_pic`,a.`admin_num`,a.`admin_email`,a.`admin_tel`,a.`update_time`,a.`status`,ag.`group_name`')
                ->withattr('head_pic',function($value,$data){
                  if($value){
                    return getShowUrl($value);
                  }
                })
                ->page($page, $limit)
                ->select();
            $count = $adminModel->alias('a')->where($condition)->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $count;
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        return View::fetch();
    }

    /**
     * @xk 管理员添加
     *
     * @method adminCreate
     *
     * @param AdminGroupModel $adminGroupModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:37:04+080
     */
    public function adminCreate(AdminGroupModel $adminGroupModel)
    {
        $admin_group_list = $adminGroupModel->where([['status', '=', 1]])->field('`admin_group_id`,`group_name`')->select();

        return View::fetch('', ['admin_group_list' => $admin_group_list]);
    }

    /**
     * @xk 管理员编辑
     *
     * @method adminEdit
     *
     * @param AdminGroupModel $adminGroupModel [description]
     * @param AdminModel      $adminModel      [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:37:45+080
     */
    public function adminEdit(AdminGroupModel $adminGroupModel, AdminModel $adminModel)
    {
        $param = request()->param();
        $admin_id = isset($param['admin_id']) ? $param['admin_id'] : 0;
        if ($admin_id <= 0) {
            $this->error('请选择需要操作的管理员');
        }
        $admin_group_list = $adminGroupModel->where([['status', '=', 1]])->field('`admin_group_id`,`group_name`')->select();
        $info = $adminModel
                ->field('*,`head_pic` as show_head_pic')
                ->withattr('show_head_pic',function($value,$data){
                  if($value){
                    return getShowUrl($value);
                  }
                })
                ->find($admin_id);

        return View::fetch('', ['info' => $info, 'admin_group_list' => $admin_group_list]);
    }

    /**
     * @xk 管理员保存
     *
     * @method adminSave
     *
     * @param AdminModel $adminModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:38:11+080
     */
    public function adminSave(AdminModel $adminModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '加载成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $check_result = $adminModel->validate($param, $act);
            switch ($act) {
          case 'create':
            $res = $adminModel->create($param);
            break;
          case 'edit':
            $res = $adminModel->find($param['admin_id'])->save($param);
            break;
        }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 管理员信息动态保存
     *
     * @method adminChanageValue
     *
     * @param AdminModel $adminModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:38:46+080
     */
    public function adminChanageValue(AdminModel $adminModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
              throw new \think\Exception("请选择需要修改的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $adminModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 管理员删除
     *
     * @method adminDestroy
     *
     * @param AdminModel $adminModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:39:18+080
     */
    public function adminDestroy(AdminModel $adminModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
              throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $adminModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // +-----------------
    // | 操作日志管理
    // +-----------------

    /**
     * @xk 操作日志列表
     *
     * @method adminLog
     *
     * @param AdminLogModel $adminLogModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-08T17:39:57+080
     */
    public function adminLog(AdminLogModel $adminLogModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            // $login_num = Session::has('admin_num') ? Session::get('admin_num') : 'xingkong';
            $page = isset($param['page']) ? (int) $param['page'] : 1;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 30;
            $condition = [];
            // if($login_num != config('manage.suppler_admin_num')){
            //   $condition[] = ['al.admin_num', '=', $login_num];
            // }
            $list = $adminLogModel
                ->alias('al')
                ->where($condition)
                ->page($page, $limit)
                ->order(['create_time desc'])
                ->select();
            $count = $adminLogModel->alias('al')->where($condition)->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $count;
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        return View::fetch();
    }

    /**
     * @xk 清除操作记录
     *
     * @method adminLogClear
     *
     * @param AdminLogModel $adminLogModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-21T18:38:24+080
     */
    public function adminLogClear(AdminLogModel $adminLogModel)
    {
        Db::startTrans();
        try {
            $login_num = Session::has('admin_num') ? Session::get('admin_num') : 'xingkong';
            if ($login_num && $login_num == config('manage.suppler_admin_num')) {
              clearResetDb('admin_log');
            }else{
              $res = $adminLogModel->destroy(function($query) use ($login_num){
                $query->where([['admin_num','=',$login_num]]);
              });
            }
            Db::commit();
            $this->result(200, '请求成功', 200, '清理日志成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->result(200, '请求成功', 404, $e->getMessage());
        }
    }
}
